﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Net;
using System.Threading;

namespace B13_Ex02_David_300512340_Alexey_321203689
{
    public class AlbumFormLogic : IAlbumLogic
    {
        public void SaveAlbum(AlbumWrapper i_SelectedAlbum, string i_Path, string i_PictureName)
        {
            if (pathIsValid(i_Path))
            {
                i_SelectedAlbum.SaveAlbum(i_SelectedAlbum, i_Path, i_PictureName);
            }
        }

        public void SaveSelectedPhotos(string i_Path, string i_PictureName, ListBox i_ListBoxPictures)
        {
            int imageCounter = 1; // If there is more than one photo, number the photos.
            string photoName = i_PictureName == string.Empty ? "facebookImage" : i_PictureName;
            string fullPhotoName = i_ListBoxPictures.SelectedItems.Count == 1 ?
                photoName : string.Format("{0}{1}", photoName, imageCounter);

            if (pathIsValid(i_Path))
            {
                MessageBox.Show(null, "Saving photos, please wait.", "Save Photos", MessageBoxButtons.OK, MessageBoxIcon.Information);
                foreach (PhotoWrapper photo in i_ListBoxPictures.SelectedItems)
                {
                    photo.SavePhoto(photo, i_Path, fullPhotoName);
                    imageCounter++;
                    fullPhotoName = string.Format("{0}{1}", photoName, imageCounter);
                }

                MessageBox.Show(null, "Done saving photos.", "Save Photos", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public List<Image> PhotosPreLoader(List<PhotoWrapper> i_PhotosList)
        {
            List<Image> imagesList = new List<Image>();

            foreach (PhotoWrapper photo in i_PhotosList)
            {
                imagesList.Add(getImageFromURL(photo.GetPhotoURL));
            }

            return imagesList;
        }

        private bool pathIsValid(string i_Path)
        {
            return i_Path != string.Empty;
        }

        private Bitmap getImageFromURL(string i_StringURL)
        {
            HttpWebRequest myRequest;
            HttpWebResponse myResponse;

            myRequest = (HttpWebRequest)WebRequest.Create(i_StringURL);
            myRequest.Method = "GET";
            myResponse = (HttpWebResponse)myRequest.GetResponse();
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
            myResponse.Close();

            return bmp;
        }
    }
}
